#!/bin/bash

#set -x
#set -u
#src: https://superuser.com/questions/323119/how-can-i-normalize-audio-using-ffmpeg

if test ! -x "`which bc`"; then
  echo "can't find 'bc' command"
  exit 3
fi

destdir="normalized_ones"

mkdir -p "$destdir"

failedlist="${destdir}/failed.lst"
echo "# Autogenerated on `date`" > "$failedlist"

ignoredlist="${destdir}/move_the_ignored.bash"
echo "#!/bin/bash" > "$ignoredlist"
echo "# Autogenerated on `date`" >> "$ignoredlist"
chmod a+x -- "$ignoredlist"

#ignored because they are already normalized(or they are clipping already!)
oktogolist="${destdir}/execmetonormalize.bash"
echo "#!/bin/bash" > "$oktogolist"
echo "# Autogenerated on `date`" >> "$oktogolist"
chmod a+x -- "$oktogolist"

fname="`realpath "$1"`"
if test -z "$fname"; then
  echo "please provide input file args"
  exit 1
fi

while test -n "$fname"; do
  if test ! -f "$fname"; then
    echo "" >> "$failedlist"
    echo "# file not found or not a regular file" >> "$failedlist"
    echo "$fname" >> "$failedlist"
  else
    maxvol="`getmaxvolume "$fname"`"
    if test -z "$maxvol"; then
      echo "" >> "$failedlist"
      echo "# maxvol=$maxvol" >> "$failedlist"
      echo "$fname" >> "$failedlist"
    else
      pm="`echo "$maxvol / 1" | bc`"
      if test "${pm}0" -lt 0; then
        positive="`echo "$maxvol * -1" | bc`"
        echo "" >> "$oktogolist"
        echo "# maxvol=$maxvol" >> "$oktogolist"
#        echo "audionormalize \"$fname\"" >> "$oktogolist"
#        dir="`dirname "$infile"`"
        infnameonly="${fname##*/}"
        #script is already in ${destdir} so we don't prepend it to dest
        echo "ffmpeg -i \"$fname\" -af \"volume=${positive}dB\" \"${infnameonly}.mp3\"" >> "$oktogolist"
        #FIXME: need proper escaping! else filenames containing " will break the above, right? and what if they contained $ etc.
      else
        #already normalized:
        echo "" >> "$ignoredlist"
        echo "# maxvol=$maxvol" >> "$ignoredlist"
        #we're already in ${destdir}
        echo "mv \"$fname\" ." >> "$ignoredlist"
      fi
    fi
  fi

  shift
  fname="`realpath "$1" 2>/dev/null`"
done
